<?php
/** 
 * 红包
 * Author:zhang
 *
 */

namespace Api\Controller;

class RedbagController extends ApiController{
	public function __construct(){
    	parent::__construct();
    	/** 测试不判断登录 modify by zhang 2016 start  **/
    	if (!I('mytest')) {
	        !api_login() && response(-94);
	        !passed_login() && response(-95);
	        !only_login() && response(-96);
    	}
    	/** 测试不判断登录 modify by zhang 2016 end **/
	}
    /**
     * 发红包
     * num  红包数量
     * price  红包金额
     * info 留言
     * type 类型:1拼手气，2普通
     */
    //发红包
    function add(){
		$fields = array('price','type','num');
		params_exist($fields);
		$price = floatval(I('price'));
		if ($price <= 0) {
			response(-9,array(),"红包金额为空");
		}
		$m_user = M("member");
		$user_amount = $m_user->where(array('uid'=>API_UID))->getField('amount');
		if ($user_amount <= $price) {
			response(-2,'',"余额不足");
		}
		$m_user -> startTrans();
		try{
			$r1 = $m_user->where(array('uid'=>API_UID))->setDec('amount',$price);
            /* 添加资金流水记录 modify by liujb 20170208 start */
            addCapitalflow('发红包',"-".$price,API_UID);
            /* 添加资金流水记录 modify by liujb 20170208 end */
			$data = M('redbag')->create();
            $data['balance'] = $data['price'];
            $data['time']     = NOW_TIME;
            $data['uid']      = API_UID;
			$r2 = M('redbag')->add($data);
			if ($r1 && $r2) {
				$m_user->commit();
                $result = array(
                    'rid'	=> $r2
                );
				response(1,$result,"操作成功");
			}else{
				$m_user->rollback();
				response(-2,"操作失败");
			}
		}catch(Exception $e){
			$m_user->rollback();
			response(-2,"操作失败");
		}
    }

    /**
     * 抢红包状态
     */
    function qiangstatus(){
        $fields = array('rid');
        params_exist($fields);
        $rid = I('rid',0);
        $uid = API_UID;
        $m_user = M('member');
        $redbag_info = M('redbag')->alias('r')
            ->field("r.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on r.uid=m.uid')
            ->where(array('r.id'=>$rid))
            ->find();
        $redbag_info['avatar_path'] = get_url($redbag_info['avatar']);
        $price = 0;
        if (empty($redbag_info)) {
            response(-2,'没有红包记录');
        }

        $check = M("redbag_list")->where(array('rid' => $rid, 'uid' => $uid))->count();
        if ($check == 0) {
            $redstatus = '1';//没有抢
            $msg="没有抢";
            if($redbag_info['balance'] == 0) {
                $redstatus = '3';//抢完了
                $msg="抢完了";
            }
        } else {
            $redstatus = '2';//抢过了
            $msg="抢过了";
        }
        $myred_list = M('redbag_list')->alias('rl')
            ->field("rl.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on rl.uid=m.uid')
            ->where(array('rl.rid'=>$rid, 'rl.uid' => $uid))
            ->select();
        $redbag_list = M('redbag_list')->alias('rl')
            ->field("rl.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on rl.uid=m.uid')
            ->where(array('rl.rid'=>$rid))
            ->order('rl.time desc')
            ->select();

        foreach($redbag_list as &$redbag){  //获取头像
            $redbag['avatar_path'] = get_url($redbag['avatar']);
        }

        $result = array(
            'list'	  => $redbag_list,
            'mylist' => $myred_list,
            'info'	  => $redbag_info,
            'redstatus' => $redstatus
        );
        response(1,$result,$msg);
    }
    //抢红包
    function qiang(){
    	$fields = array('rid');
    	params_exist($fields);
    	$rid = I('rid',0);
    	$uid = API_UID;
    	$m_user = M('member');
    	$redbag_info = M('redbag')->alias('r')
    					->field("r.*,m.nickname,m.avatar")
    					->join('left join __MEMBER__ m on r.uid=m.uid')
    					->where(array('r.id'=>$rid))
    	                ->find();
        $redbag_info['avatar_path'] = get_url($redbag_info['avatar']);
    	$price = 0;
    	if (empty($redbag_info)) {
    		response(-2,'没有红包记录');
    	}elseif ($redbag_info['balance'] > 0) {
    		$check = M("redbag_list")->where(array('rid'=>$rid,'uid'=>$uid))->count();
    		if ($check == 0) {
                $redstatus ='1';//没有抢
    			$m_user->startTrans();
    			try{
    				$num = M('redbag_list')->where(array('rid'=>$rid))->count();
    				if(!$num){
    				    $num = 1;
                    }
    				$last_num = $redbag_info['num'] - $num;
    				if ($last_num <= 0) {
    					$price = $redbag_info['balance'];
    				}else{
    					if ($redbag_info['type'] == 2) { // 普通红包
    						$price = round($redbag_info['price']/$redbag_info['num'],2);
    					}else{ //手气红包
    						$price = rand(1,$redbag_info['balance'] * 100 - $last_num) / 100;
    					}
    				}
					// 添加抢红包记录
					$data = array(
						'rid'	=> $rid,
						'uid'	=> $uid,
						'price'	=> $price,
						'time'	=> NOW_TIME
					);
					$r1 = M('redbag_list')->add($data);
					// 更新红包信息
					$r2 = M('redbag')->where(array('id'=>$rid))->setDec('balance',$price);
					// 用户金额增加
					$r3 = $m_user->where(array('uid'=>$uid))->setInc('amount',$price);
                    /* 添加资金流水记录 modify by liujb 20170209 start */
                    addCapitalflow('抢红包',"+".$price,$uid);
                    /* 添加资金流水记录 modify by liujb 20170209 end */
					// 有剩余红包，已添加红包记录，已更新红包信息和用户信息，提交数据
					if ( $r1 && $r2 && $r3) {
						$m_user->commit();
						$msg = '恭喜抢到红包';
					}else{
	    				$m_user->rollback();
						$price = 0;
						$msg = "抢红包失败";
					}
    			}catch(Exception $e){
    				$m_user->rollback();
					$price = 0;
					$msg = "抢红包失败";
    			}
    		}else{
                $redstatus ='2';//已抢过
            }
    	}else{
    	    $redstatus ='3';  //抢完了
        }

        //抢过跟没抢到的返回
    	$redbag_list = M('redbag_list')->alias('rl')
    					->field("rl.*,m.nickname,m.avatar")
    					->join('left join __MEMBER__ m on rl.uid=m.uid')
    					->where(array('rl.rid'=>$rid))
    					->select();
        $myredbag_list = M('redbag_list')->alias('rl')
            ->field("rl.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on rl.uid=m.uid')
            ->where(array('rl.rid'=>$rid,'rl.uid'=>$uid))
            ->select();
    	$result = array(
    		'list'	=> $redbag_list,
            'mylist'=>$myredbag_list,
    		'info'	=> $redbag_info,
    		'price'	=> $price
    	);
    	response(1,$result,$msg);
    }
    //我发出的红包
    function issue(){
    	// 发出的红包
    	$send = array();
    	$send['info'] = M('redbag')->field('sum(price) as price,count(id) as num')->where(array('uid'=>API_UID))->find();
    	$send['list'] = M('redbag')->alias('r')
            ->field("r.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on r.uid=m.uid')
            ->where(array('r.uid'=>API_UID))
            ->select();
        foreach($send['list'] as &$sendlist){  //获取头像
            $sendlist['avatar_path'] = get_url($sendlist['avatar']);
            $znum  = M('redbag')->field('num')->where(array('id'=>$sendlist['id']))->find();
            $lqnum = M('redbag_list')->field('count(id) as lqnum')->where(array('rid'=>$sendlist['id']))->find();
            $sendlist['znum'] = $znum['num'];
            $sendlist['lqnum'] = $lqnum['lqnum'];
        }
    	// 收到的红包
    	$received = array();
    	$received['info'] = M('redbag_list')->field('sum(price) as price,count(id) as num')->where(array('uid'=>API_UID))->find();
    	$received['list'] = M('redbag_list')->alias('rl')
            ->field("rl.*,m.nickname,m.avatar")
            ->join('left join __MEMBER__ m on rl.uid=m.uid')
            ->where(array('rl.uid'=>API_UID))
            ->select();

    	$data = array(
    		'send'=>$send,
    		'received'=>$received
    	);
    	response(1,$data);
    }
    //群主发新人红包
    function newred(){
    	params_exist(array('hid','uid','price','num'));
    	$hid = I('hid');
    	$uid = I('uid');
    	$price = floatval(I('price'));
    	$num = intval(I('num'));

		if ($price <= 0) {
			response(-9,"红包金额为空");
		}
        //判断余额是否足够
		$m_user = M("member");
		$user_amount = $m_user->where(array('uid'=>$uid))->getField('amount');
		if ($user_amount <= $price) {
			response(-2,'',"余额不足");
		}
		// 判断群是否发送过红包
    	$rid = M("herd")->where(array('id'=>$hid))->getField('red_id');
    	$m_user->startTrans();
    	try {
    		if ($rid) {
    			$data = array(
    				'id'		=> $rid,
    				'balance'	=> array('exp','balance + '.$price),
    				'price'		=> array('exp','price + ' .$price),
    				'num'		=> array('exp','num + '. $num)
    			);
    			$r1 = M('redbag')->save($data);
    		}else{
    			$data = array(
    				'uid'   => $uid,
                    'num'   => $num,
                    'price' => $price,
                    'balance'=>$price,
                    'info'  => "新人红包",
                    'time'  => NOW_TIME
    			);
                $rid = M('redbag')->add($data);
                // 更新群红包信息
                if ($rid) {
                    $r1 = M('herd')->save(array('id'=>$hid,'red_id'=>$rid));
                }else{
                    response(-9);
                }
    		}
    	} catch (Exception $e) {
    		response(-9);
    	}
        // 更新用户余额
        $r2 = $m_user->where(array('id'=>$uid))->setDec('amount',$price);
        /* 添加资金流水记录 modify by liujb 20170209 start */
        addCapitalflow('群主发新人红包',"-".$price,$uid);
        /* 添加资金流水记录 modify by liujb 20170209 end */
        if ($r1 && $r2) {
            $m_user->commit();
        }else{
            $m_user->rollback();
        }
        response(1,'红包发送成功');
    }
}